package com.hupu.jrs.api.forum

import android.content.Context
import android.text.TextUtils
import android.util.Log
import com.hupu.jrs.bean.*
import com.hupu.jrs.components.retrofit.FastJsonConverterFactory
import com.hupu.jrs.components.retrofit.RequestHelper
import com.hupu.jrs.components.storage.UserStorage
import com.hupu.jrs.db.ThreadInfo
import com.hupu.jrs.util.SettingPrefUtil
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import rx.Observable
import rx.schedulers.Schedulers
import java.io.File
import java.util.*

/**
 * Created by Stark.Tony on 2018/3/18.
 */
class ForumApi(private val mRequestHelper: RequestHelper, private val mUserStorage: UserStorage,
               mOkHttpClient: OkHttpClient, private val mContext: Context) {

    private val mForumService: ForumService

    /**
     * 获取所有论坛列表
     */
    val forums: Observable<ForumsData>
        get() {
            val params = mRequestHelper.httpRequestMap
            val sign = mRequestHelper.getRequestSign(params)
            return mForumService.getForums(sign, params).subscribeOn(Schedulers.io())
        }

    /**
     * 获取用户收藏的论坛列表
     */
    val myForums: Observable<MyForumsData>
        get() {
            val params = mRequestHelper.httpRequestMap
            val sign = mRequestHelper.getRequestSign(params)
            return mForumService.getMyForums(sign, params).subscribeOn(Schedulers.io())
        }

    init {
        val retrofit = Retrofit.Builder().addConverterFactory(FastJsonConverterFactory.create())
                .client(mOkHttpClient)
                .baseUrl(BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build()
        mForumService = retrofit.create(ForumService::class.java)
    }

    /**
     * 获取论坛帖子列表
     *
     * @param fid      论坛id，通过getForums接口获取
     * @param lastTid  最后一篇帖子的id
     * @param lastTamp 时间戳
     * @param type     加载类型  1 按发帖时间排序  2 按回帖时间排序
     */
    fun getThreadsList(fid: String, lastTid: String, lastTamp: String,
                       type: String): Observable<ThreadListData> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        params.put("fid", fid)
        params.put("lastTid", lastTid)
        params.put("isHome", "1")
        params.put("stamp", lastTamp)
        params.put("password", "0")
        params.put("special", "0")
        params.put("type", type)
        val sign = mRequestHelper.getRequestSign(params)
        return mForumService.getThreadsList(sign, params).subscribeOn(Schedulers.io())
    }

    /**
     * 添加关注
     *
     * @param fid 论坛id
     */
    fun addAttention(fid: String): Observable<AttendStatusData> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        params.put("fid", fid)
        params.put("uid", mUserStorage.uid)
        val sign = mRequestHelper.getRequestSign(params)
        return mForumService.addAttention(sign, params).subscribeOn(Schedulers.io())
    }

    /**
     * 取消关注
     *
     * @param fid 论坛id
     */
    fun delAttention(fid: String): Observable<AttendStatusData> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        params.put("fid", fid)
        params.put("uid", mUserStorage.uid)
        val sign = mRequestHelper.getRequestSign(params)
        return mForumService.delAttention(sign, params).subscribeOn(Schedulers.io())
    }

    /**
     * 获取论坛关注状态
     *
     * @param fid 论坛id
     */
    fun getAttentionStatus(fid: String): Observable<AttendStatusData> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        params.put("fid", fid)
        params.put("uid", mUserStorage.uid)
        val sign = mRequestHelper.getRequestSign(params)
        return mForumService.getAttentionStatus(sign, params).subscribeOn(Schedulers.io())
    }

    /**
     * 获取帖子详情
     *
     * @param tid  帖子id
     * @param fid  论坛id
     * @param page 页数
     * @param pid  回复id
     */
    fun getThreadSchemaInfo(tid: String, fid: String, page: Int,
                            pid: String): Observable<ThreadSchemaInfo> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        if (!TextUtils.isEmpty(tid)) {
            params.put("tid", tid)
        }
        if (!TextUtils.isEmpty(fid)) {
            params.put("fid", fid)
        }
        params.put("page", page.toString() + "")
        if (!TextUtils.isEmpty(pid)) {
            params.put("pid", pid)
        }
        params.put("nopic", if (SettingPrefUtil.getLoadPic(mContext)) "0" else "1")
        val sign = mRequestHelper.getRequestSign(params)
        return mForumService.getThreadSchemaInfo(sign, params).subscribeOn(Schedulers.io())
    }

    fun getThreadInfo(tid: String, fid: String, page: Int, pid: String): Observable<ThreadInfo> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        if (!TextUtils.isEmpty(tid)) {
            params.put("tid", tid)
        }
        if (!TextUtils.isEmpty(fid)) {
            params.put("fid", fid)
        }
        params.put("page", page.toString() + "")
        if (!TextUtils.isEmpty(pid)) {
            params.put("pid", pid)
        }

        return mForumService.getThreadInfo(params)
    }

    fun getThreadReplyList(tid: String, fid: String, page: Int): Observable<ThreadReplyData> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        if (!TextUtils.isEmpty(tid)) {
            params.put("tid", tid)
        }
        if (!TextUtils.isEmpty(fid)) {
            params.put("fid", fid)
        }
        params.put("page", page.toString() + "")
        return mForumService.getsThreadReplyList(params)
    }

    fun getThreadLightReplyList(tid: String, fid: String): Observable<ThreadLightReplyData> {
        val params = mRequestHelper.httpRequestMap.toMutableMap().toMutableMap()
        if (!TextUtils.isEmpty(tid)) {
            params.put("tid", tid)
        }
        if (!TextUtils.isEmpty(fid)) {
            params.put("fid", fid)
        }
        return mForumService.getThreadLightReplyList(params)
    }

    fun addLight(tid: String, fid: String, pid: String): Observable<BaseData> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        if (!TextUtils.isEmpty(tid)) {
            params.put("tid", tid)
        }
        if (!TextUtils.isEmpty(fid)) {
            params.put("fid", fid)
        }
        params.put("pid", pid)
        return mForumService.addLight(params).subscribeOn(Schedulers.io())
    }

    fun addRuLight(tid: String, fid: String, pid: String): Observable<BaseData> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        if (!TextUtils.isEmpty(tid)) {
            params.put("tid", tid)
        }
        if (!TextUtils.isEmpty(fid)) {
            params.put("fid", fid)
        }
        params.put("pid", pid)
        return mForumService.addRuLight(params).subscribeOn(Schedulers.io())
    }

    /**
     * 发新帖
     *
     * @param title   标题
     * @param content 内容
     * @param fid     论坛id
     */
    fun addThread(title: String, content: String, fid: String): Observable<PostData> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        params.put("title", title)
        params.put("content", content)
        params.put("fid", fid)
        val sign = mRequestHelper.getRequestSign(params)
        params.put("sign", sign)
        return mForumService.addThread(params).subscribeOn(Schedulers.io())
    }

    /**
     * 评论或者回复
     *
     * @param tid     帖子id
     * @param fid     论坛id
     * @param pid     回复id（评论时为空，回复某条回复的为回复的id）
     * @param content 内容
     */
    fun addReplyByApp(tid: String, fid: String, pid: String, content: String): Observable<PostData> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        params.put("tid", tid)
        params.put("content", content)
        params.put("fid", fid)
        if (!TextUtils.isEmpty(pid)) {
            params.put("quotepid", pid)
            params.put("boardpw", "")
        }
        val sign = mRequestHelper.getRequestSign(params)
        params.put("sign", sign)
        Log.d("groupApi", "gson.toJson(params):" + params)
        return mForumService.addReplyByApp(params).subscribeOn(Schedulers.io())
    }

    /**
     * 收藏帖子
     *
     * @param tid 帖子id
     */
    fun addCollect(tid: String): Observable<CollectData> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        params.put("tid", tid)
        val sign = mRequestHelper.getRequestSign(params)
        return mForumService.addCollect(sign, params).subscribeOn(Schedulers.io())
    }

    /**
     * 取消收藏帖子
     *
     * @param tid 帖子id
     */
    fun delCollect(tid: String): Observable<CollectData> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        params.put("tid", tid)
        val sign = mRequestHelper.getRequestSign(params)
        return mForumService.delCollect(sign, params).subscribeOn(Schedulers.io())
    }

    /**
     * (1, "广告或垃圾内容");
     * (2, "色情暴露内容");
     * (3, "政治敏感话题");
     * (4, "人身攻击等恶意行为");
     */
    fun submitReports(tid: String, pid: String, type: String, content: String): Observable<BaseData> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        if (!TextUtils.isEmpty(tid)) {
            params.put("tid", tid)
        }
        if (!TextUtils.isEmpty(pid)) {
            params.put("pid", pid)
        }
        params.put("type", type)
        params.put("content", content)
        val sign = mRequestHelper.getRequestSign(params)
        return mForumService.submitReports(sign, params).subscribeOn(Schedulers.io())
    }

    /**
     * 获取推荐帖子列表
     */
    fun getRecommendThreadList(lastTid: String, lastTamp: String): Observable<ThreadListData> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        params.put("lastTid", lastTid)
        params.put("isHome", "1")
        params.put("stamp", lastTamp)
        val sign = mRequestHelper.getRequestSign(params)
        return mForumService.getRecommendThreadList(sign, params).subscribeOn(Schedulers.io())
    }

    /**
     * 获取论坛消息列表
     *
     * @param lastTid 上一条消息id
     * @param page    页数
     */
    fun getMessageList(lastTid: String, page: Int): Observable<MessageData> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        params.put("messageID", lastTid)
        params.put("page", page.toString())
        params.put("uid", mUserStorage.uid)
        val sign = mRequestHelper.getRequestSign(params)
        return mForumService.getMessageList(sign, params).subscribeOn(Schedulers.io())
    }

    /**
     * 阅读某条消息
     *
     * @param id 消息id
     */
    fun delMessage(id: String): Observable<BaseData> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        params.put("id", id)
        val sign = mRequestHelper.getRequestSign(params)
        return mForumService.delMessage(sign, params).subscribeOn(Schedulers.io())
    }

    /**
     * 上传图片
     *
     * @param path 图片地址
     */
    fun upload(path: String): Observable<UploadData> {
        val file = File(path)
        val requestFile = RequestBody.create(MediaType.parse(getContentType(path)), file)
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        val sign = mRequestHelper.getRequestSign(params)
        params.put("sign", sign)
        val requestBody = HashMap<String, RequestBody>()
        for (key in params.keys) {
            val value = params.get(key)
            requestBody.put(key, RequestBody.create(MediaType.parse("multipart/form-data"), value))
        }
        val body = MultipartBody.Part.createFormData("files", file.name, requestFile)
        return mForumService.upload(body, requestBody)
    }

    private fun getContentType(str: String?): String? {
        if (str == null) {
            return null
        }
        if (str.endsWith(".jpe") || str.endsWith(".JPE") || str.endsWith(".JPEG") || str.endsWith(
                ".jpeg") || str.endsWith(".jpg") || str.endsWith(".JPG")) {
            return "image/jpeg"
        }
        if (str.endsWith(".png") || str.endsWith(".PNG")) {
            return "image/png"
        }
        return if (str.endsWith(".gif")) {
            "image/gif"
        } else null
    }

    /**
     * 检查权限
     *
     * @param fid    论坛id
     * @param tid    帖子id
     * @param action threadPublish  threadReply
     */
    fun checkPermission(fid: String, tid: String, action: String): Observable<PermissionData> {
        val params = mRequestHelper.httpRequestMap.toMutableMap()
        if (!TextUtils.isEmpty(fid)) {
            params.put("fid", fid)
        }
        if (!TextUtils.isEmpty(tid)) {
            params.put("tid", tid)
        }
        if (!TextUtils.isEmpty(action)) {
            params.put("action", action)
        }
        val sign = mRequestHelper.getRequestSign(params)
        return mForumService.checkPermission(sign, params).subscribeOn(Schedulers.io())
    }

    companion object {

        internal val BASE_URL = "http://bbs.mobileapi.hupu.com/1/7.0.8/"
    }
}
